package com.chuang.bootplus.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuang.bootplus.base.constant.Constant;
import com.chuang.bootplus.base.database.JwtModel;
import com.chuang.bootplus.base.enumerate.HttpStatusEnum;
import com.chuang.bootplus.base.exception.BusException;
import com.chuang.bootplus.base.utils.ApiResponse;
import com.chuang.bootplus.base.utils.BeanUtil;
import com.chuang.bootplus.base.utils.JwtUtil;
import com.chuang.bootplus.entity.RelUserMedal;
import com.chuang.bootplus.entity.UserInfo;
import com.chuang.bootplus.mapper.UserInfoMapper;
import com.chuang.bootplus.po.bean.BeanSavePO;
import com.chuang.bootplus.po.WxLoginPO;
import com.chuang.bootplus.po.bean.BeanSelectPO;
import com.chuang.bootplus.service.RelUserMedalService;
import com.chuang.bootplus.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.chuang.bootplus.vo.BeanListVO;
import com.chuang.bootplus.vo.BeanSelectVO;
import lombok.RequiredArgsConstructor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-07-04
 */
@Service("userService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    final WxMaService wxService;
    final RelUserMedalService relUserMedalService;

    @Override
    public ApiResponse loginByWx(WxLoginPO po) {
        String code = po.getCode();
        String code2 = po.getCode();
        if(code==null) {
            throw new BusException(HttpStatusEnum.RE_CODE_PARAM_ERROR);
        }
        String sessionKey = null;
        String openId = null;

        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusException("请求微信接口出错，登录失败！");
        }

        if (sessionKey == null || openId == null) {
            throw new BusException("获取sessionKey或openId失败！");
        }

        UserInfo user = getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getAppId,openId));
        if(user==null){
            user=new UserInfo();
            user.setAppId(openId);
            save(user);
        }else {
            saveUserInfo(user);
        }
        return new ApiResponse(user);
    }

    @Override
    public ApiResponse<Void> saveBean(BeanSavePO po) {

        if (po.getBeanSaveId() == null||po.getUserId()==null) {
            throw new BusException(HttpStatusEnum.RE_CODE_PARAM_ERROR, "参数不能为空！");
        }

        UserInfo info = getById(po.getUserId());
        if (info == null) {
            return new ApiResponse<>(HttpStatusEnum.RE_CODE_NO_HAVE_OBJECT);
        }

        if (po.getBeanSaveId().equals(Constant.LOOK_FRONT_TIPS_BEAN)){
            updateById(info.setCarbonBean(info.getCarbonBean()+ Constant.LOOK_FRONT_TIPS_BEAN));
        }else if (po.getBeanSaveId().equals(Constant.SIGN_IN_BEAN)){
            updateById(info.setCarbonBean(info.getCarbonBean()+ Constant.SIGN_IN_BEAN));
        }else if (po.getBeanSaveId().equals(Constant.TOPIC_SAVE_BEAN)){
            updateById(info.setCarbonBean(info.getCarbonBean()+ Constant.TOPIC_SAVE_BEAN));
        }else {
            throw new BusException(HttpStatusEnum.RE_CODE_PARAM_ERROR, "参数异常！");
        }

        RelUserMedal one = relUserMedalService.getOne(new LambdaQueryWrapper<RelUserMedal>()
                .eq(RelUserMedal::getMedalId, Constant.MEDAL_TYPE_TWO)
                .eq(RelUserMedal::getUserId,po.getUserId()));
        if (!(one != null && po.getUserId().equals(one.getUserId())&&one.getMedalId().equals(Constant.MEDAL_TYPE_TWO))) {
            if (info.getCarbonBean()>=Constant.BEAN_NUM1){
                relUserMedalService.save(new RelUserMedal().setUserId(po.getUserId()).setMedalId(Constant.MEDAL_TYPE_TWO));
            }
        }

        RelUserMedal two = relUserMedalService.getOne(new LambdaQueryWrapper<RelUserMedal>()
                .eq(RelUserMedal::getMedalId, Constant.MEDAL_TYPE_THREE)
                .eq(RelUserMedal::getUserId,po.getUserId()));
        if (!(two != null && po.getUserId().equals(two.getUserId())&&two.getMedalId().equals(Constant.MEDAL_TYPE_THREE))) {
            if (info.getCarbonBean()>=Constant.BEAN_NUM2){
                relUserMedalService.save(new RelUserMedal().setUserId(po.getUserId()).setMedalId(Constant.MEDAL_TYPE_THREE));
            }
        }

        RelUserMedal three = relUserMedalService.getOne(new LambdaQueryWrapper<RelUserMedal>()
                .eq(RelUserMedal::getMedalId, Constant.MEDAL_TYPE_FOUR)
                .eq(RelUserMedal::getUserId,po.getUserId()));
        if (!(three != null && po.getUserId().equals(three.getUserId())&&three.getMedalId().equals(Constant.MEDAL_TYPE_FOUR))) {
            if (info.getCarbonBean()>=Constant.BEAN_NUM3){
                relUserMedalService.save(new RelUserMedal().setUserId(po.getUserId()).setMedalId(Constant.MEDAL_TYPE_FOUR));
            }
        }

        return new ApiResponse<>();
    }

    @Override
    public ApiResponse<BeanListVO> beanList() {
        List<UserInfo> list = list(new LambdaQueryWrapper<UserInfo>().orderByDesc(UserInfo::getCarbonBean));
        List<BeanListVO> beanListVOS = BeanUtil.listA2ListB(list, BeanListVO.class);

        Long id = beanListVOS.get(0).getId();
        RelUserMedal one = relUserMedalService.getOne(new LambdaQueryWrapper<RelUserMedal>()
                .eq(RelUserMedal::getMedalId, Constant.MEDAL_TYPE_ONE)
                .eq(RelUserMedal::getUserId,id));

        if (!(one != null && id.equals(one.getUserId())&&one.getMedalId().equals(Constant.MEDAL_TYPE_ONE))) {
            relUserMedalService.save(new RelUserMedal().setUserId(id).setMedalId(Constant.MEDAL_TYPE_ONE));
        }

        return new ApiResponse<>(beanListVOS);
    }

    @Override
    public ApiResponse<BeanSelectVO> beanSelect(BeanSelectPO po) {
        UserInfo info = getById(po.getId());
        if (info == null) {
            return new ApiResponse<>(HttpStatusEnum.RE_CODE_NO_HAVE_OBJECT);
        }
        BeanSelectVO beanSelectVO = BeanUtil.beanA2beanB(info, BeanSelectVO.class);
        return new ApiResponse<>(beanSelectVO);
    }

    @Override
    public ApiResponse<Void> saveUserInfo(UserInfo userInfo) {
        UserInfo updateUser = BeanUtil.beanA2beanB(userInfo,UserInfo.class,"carbonBean","appId");
        updateById(updateUser);
        return new ApiResponse<>();
    }

}
